﻿// <copyright file="RepairController.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace MesAPI.Controllers.Maintenance
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Text;
    using MesAPI.Extensions.AuthContext;
    using MesAPI.Models;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using Newtonsoft.Json;
    using PublicData;
    using PublicModelsAndEntities.Models.MaintenanceRecord;
    using XinjeMesProgram.Entities;
    using XinjeMesProgram.Entities.BookInfo;
    using XinjeMesProgram.Entities.Function;
    using XinjeMesProgram.Entities.Maintenance;
    using static XinjeMesProgram.Entities.RoleAndUser.CommonEnum;

    /// <summary>
    /// 维修 .
    /// </summary>
    [ApiController]
    [Authorize]
    public class RepairController : ControllerBase
    {
#pragma warning disable CS8600 // 将 null 字面量或可能为 null 的值转换为非 null 类型。
#pragma warning disable CS8601
#pragma warning disable CS8602 // 解引用可能出现空引用。
#pragma warning disable CS8604 // 引用类型参数可能为 null。
        private ResponseModel response = new();

        /// <summary>
        /// 获取维修产品列表.
        /// </summary>
        /// <param name="pageSize">每页记录条数.</param>
        /// <param name="currentPage">当前页码.</param>
        /// <param name="oneDimensionalCode">产品一维码.</param>
        /// <param name="chaoqi">时间状态.</param>
        /// <param name="oN1"> .</param>
        /// <param name="namegcs">工程师.</param>
        /// <param name="name">产品类别.</param>
        /// <param name="allocation_name">分配.</param>
        /// <param name="warehousingDate">收货日期.</param>
        /// <param name="product_category">产品部门.</param>
        /// <returns>返回列表.</returns>
        [Route("/api/v1/repair/repairList")]
        [HttpGet]
        public ResponseModel RepairList(int pageSize, int currentPage, string? oneDimensionalCode, string? chaoqi, int? oN1, string? namegcs, string? name, string? allocation_name, string? warehousingDate, int? product_category = 0)
        {
            using var context = new FactoryMesContext();
            AuthContextUser currentUser = AuthContextService.CurrentUser;

            // IQueryable <RepairModel> query = null;
            try
            {
                if (new int[] { 0, 1, 2, 3 }.Contains((int)currentUser.UserType))
                {
                    var query = from sr in context.MainsortRecord // 最高账号、主管、组长 返回的内容
                                join rp in context.RepairProduct on sr.ID equals rp.ProductId
                                join mc in context.MaintenanceCost on sr.ID equals mc.ID
                                where rp.State == "0"
                                && new[] { "3", "5" }.Contains(sr.State)
                                select new RepairModel
                                {
                                    ProductId = sr.ID,
                                    ApplyRepairTime = rp.MaintenanceEntryTime == null ? string.Empty : rp.MaintenanceEntryTime.Value.ToString("yyyy-MM-dd") ?? string.Empty,
                                    DaysOfReceipt = (DateTime.Now.Date - DateTime.Parse(sr.WarehousingDate.Substring(0, 10)).Date).Days.ToString(),
                                    Name = sr.Name,
                                    One_dimensional_code = sr.One_Dimensional_Code,
                                    Product_model = sr.Product_Model,
                                    Product_category = sr.Product_Category,
                                    Product_classification = sr.Product_Classification,
                                    Product_Name = sr.Product_Name,
                                    Guarantee = sr.Guarantee,
                                    State = sr.State,
                                    SkillManager = rp.SkillManager == "null" ? string.Empty : rp.SkillManager,
                                    AssignPersonnel = context.MesUserRole.FirstOrDefault(x => x.ID == sr.AssignPersonnelUserId).UserName ?? string.Empty,

                                    // FixUnder6 = MaintenancesQuery.GetFixUnder6(rp.Code),
                                    FixUnder6 = sr.SecondaryRepairsOr == "是" ? "是" : string.Empty,
                                    Product_handle = rp.ProductHandle,
                                    Repairornot = rp.RepairOr,
                                    FirstEnter = context.MaintenanceCost.FirstOrDefault(x => x.ID == sr.ID).Context != null ? 1 : 0,
                                    WarehousingDate = sr.WarehousingDate, // 收货时间
                                    Shipping_address = sr.Shipping_Address,
                                    Contact_information = sr.Contact_Information,
                                    RepairData = rp.Data,
                                    CustomerLevel = sr.CustomerLevel,
                                    ShippingNumber = rp.ShippingNumber,  // 发货编号
                                };
                    product_category = product_category.Equals(string.Empty) ? 0 : product_category;

                    // 按照产品类别筛选
                    if (product_category != 0)
                    {
                        string temp = string.Empty;
                        if (product_category == 2)
                        {
                            temp = "生产二部";
                        }
                        else if (product_category == 3)
                        {
                            temp = "生产三部";
                        }
                        else if (product_category == 4)
                        {
                            temp = "生产四部";
                        }

                        query = query.Where(x => x.Product_category.Equals(temp));      // 循环查找（Product_category）与之对应的数据，并替换数据     知识点：.where 方法的用法  筛选
                    }

                    // 按照一维码筛选
                    if (!string.IsNullOrEmpty(oneDimensionalCode))
                    {
                        query = query.Where(x => x.One_dimensional_code.Contains(oneDimensionalCode));   // 循环查找（One_dimensional_code）与之对应的数据，并替换数据
                    }

                    if (!string.IsNullOrEmpty(namegcs))
                    {
                        query = query.Where(x => x.AssignPersonnel.Contains(namegcs));
                    }

                    // 按照客户名称筛选
                    if (!string.IsNullOrEmpty(name))
                    {
                        query = query.Where(x => x.Name.Contains(name));
                    }

                    // 按照是否分配筛选,
                    if (allocation_name == "未分配")
                    {
                        query = query.Where(x => x.AssignPersonnel == string.Empty);
                    }
                    else if (allocation_name == "已分配")
                    {
                        query = query.Where(x => x.AssignPersonnel != string.Empty);
                    }

                    // int count = query.ToList().Count();
                    List<RepairModel> result = query.ToList();

                    if (!string.IsNullOrEmpty(chaoqi))
                    {
                        if (chaoqi == "正常")
                        {
                            result = result.Where(x => (DateTime.Now - DateTime.ParseExact(x.WarehousingDate[..10], "yyyy/MM/dd", CultureInfo.InvariantCulture)).Days < 5).ToList();
                        }
                        else if (chaoqi == "将超期")
                        {
                            result = result.Where(x => (DateTime.Now - DateTime.ParseExact(x.WarehousingDate[..10], "yyyy/MM/dd", CultureInfo.InvariantCulture)).Days <= 7 &&
                            (DateTime.Now - DateTime.ParseExact(x.WarehousingDate[..10], "yyyy/MM/dd", CultureInfo.InvariantCulture)).Days >= 5).ToList();
                        }
                        else if (chaoqi == "超期")
                        {
                            result = result.Where(x => (DateTime.Now - DateTime.ParseExact(x.WarehousingDate[..10], "yyyy/MM/dd", CultureInfo.InvariantCulture)).Days > 7).ToList();
                        }
                    }

                    // 按照日期筛选
                    if (!string.IsNullOrEmpty(warehousingDate))
                    {
                        string[] wareho = warehousingDate.Split(',');
                        result = result.Where(x => DateTime.Compare(DateTime.Parse(x.WarehousingDate[..10]), DateTime.Parse(wareho[0])) >= 0).ToList();
                        result = result.Where(x => DateTime.Compare(DateTime.Parse(x.WarehousingDate[..10]), DateTime.Parse(wareho[1])) <= 0).ToList();

                        // query = query.Where(x => x.WarehousingDate.Contains(wareho[1]));
                        // query = query.Where(x => DateTime.Compare(DateTime.Parse(x.WarehousingDate.Substring(0, 10)), DateTime.Parse(wareho[1])) <= 0);
                    }

                    result.Sort((a, b) => DateTime.Parse(b.ApplyRepairTime == string.Empty ? "2099-01-01 00:00:00.000" : b.ApplyRepairTime).CompareTo(DateTime.Parse(a.ApplyRepairTime == string.Empty ? "2099-01-01 00:00:00.000" : a.ApplyRepairTime)));

                    this.response.SetData(result.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList(), result.Count);

                    int count = result.Count;
                    result = result.OrderBy(x => x.Name).ToList(); // 客户名称排列
                    result = result.OrderByDescending(x => x.WarehousingDate).ToList(); // 收货时间按降序排列
                    result = result.OrderByDescending(x => x.ApplyRepairTime).ToList(); // 收费时间排序

                    this.response.SetData(result.ListPaged(currentPage, pageSize), count);

                    if (oN1 == 1)
                    {
                        StringBuilder csvContent = new();
                        csvContent.AppendLine("收货日期,维修时间,到货天数,产品处理(是否收费),发货编号,客户名称,产品编码,产品规格型号,产品组类别,保内/保外" +
                            ",状态,工程师名称,产品细分,回访记录,类型(伺服),产品内码,产品日期,二维码/外加工厂家,问题归类,故障类型,故障细分,原因细分(电机),故障原因(电机)," +
                            "编码器编码(电机),器件规格,品牌,位号,客户反应现象,维修检测现象,故障原因分析,故障处理,PCB丝印,测台标志位(驱动),报警记录,软件版本" +
                            ",运行时间h,运行时间min,备注,X电阻(数字),Y电阻(数字),绝缘电阻(数字),电容(数字),图片链接");  // 核对导出表 表头

                        foreach (var book in result)
                        {
                            // 含维修记录导出
                            if (book.RepairData != null)
                            {
                                RepairCatalogModel catalogModel = JsonConvert.DeserializeObject<RepairCatalogModel>(book.RepairData);
                                Maintenancerecords records = new();
                                var a1 = DateTime.ParseExact(DateTime.Now.ToString("yyyy/HH/dd"), "yyyy/HH/dd", CultureInfo.InvariantCulture);
                                var b1 = DateTime.ParseExact(book.WarehousingDate[..10], "yyyy/HH/dd", CultureInfo.InvariantCulture);
                                if (catalogModel.picAddress != null)
                                {
                                    for (int i = 0; i < catalogModel.picAddress.Count; i++)
                                    {
                                        records.picAddress1 = records.picAddress1 + catalogModel.picAddress[i] + ",";
                                    }
                                }

                                if (catalogModel.list != null)
                                {
                                    foreach (var book1 in catalogModel.list)
                                    {
                                        if (book1.key == "repairTime")
                                        {
                                            records.repairTime = book1.value;
                                        }

                                        if (book1.key == "back_record")
                                        {
                                            records.back_record = book1.value.Replace(",", "|");
                                        }

                                        if (book1.key == "type")
                                        {
                                            records.type = book1.value;
                                        }

                                        if (book1.key == "product_code")
                                        {
                                            records.product_code = book1.value;
                                        }

                                        if (book1.key == "product_date")
                                        {
                                            records.product_date = book1.value;
                                        }

                                        if (book1.key == "2D_factory" || book1.key == "2-Dbarcode")
                                        {
                                            records.D2_factory = book1.value;
                                        }

                                        if (book1.key == "question_classify")
                                        {
                                            records.question_classify = book1.value;
                                        }

                                        if (book1.key == "error_type")
                                        {
                                            records.error_type = book1.value;
                                        }

                                        if (book1.key == "error_detail" || book1.key == "kind")
                                        {
                                            records.error_detail = book1.value;
                                        }

                                        if (book1.key == "reason_detail")
                                        {
                                            records.reason_detail = book1.value;
                                        }

                                        if (book1.key == "error_reason")
                                        {
                                            records.error_reason = book1.value;
                                        }

                                        if (book1.key == "encrypt")
                                        {
                                            records.encrypt = book1.value;
                                        }

                                        if (book1.key == "product_size")
                                        {
                                            records.product_size = book1.value.Replace(",", "|");
                                        }

                                        if (book1.key == "brand")
                                        {
                                            records.brand = book1.value.Replace(",", "|");
                                        }

                                        if (book1.key == "position")
                                        {
                                            records.position = book1.value.Replace(",", "|");
                                        }

                                        if (book1.key == "Guarantee")
                                        {
                                            records.guarantee = book1.value;
                                        }

                                        if (book1.key == "custom_reply_phenomenon")
                                        {
                                            records.custom_reply_phenomenon = book1.value.Replace(",", "|");
                                        }

                                        if (book1.key == "repair_phenomenon")
                                        {
                                            records.repair_phenomenon = book1.value.Replace(",", "|");
                                        }

                                        if (book1.key == "reason_analysis")
                                        {
                                            records.reason_analysis = book1.value.Replace(",", "|");
                                        }

                                        if (book1.key == "alarm_record")
                                        {
                                            records.alarm_record = book1.value.Replace(",", "|");
                                        }

                                        if (book1.key == "error_deal")
                                        {
                                            records.error_deal = book1.value.Replace(",", "|");
                                        }

                                        if (book1.key == "PCBsiyin")
                                        {
                                            records.PCBsiyin = book1.value;
                                        }

                                        if (book1.key == "P172")
                                        {
                                            records.P172 = book1.value;
                                        }

                                        if (book1.key == "software_edition")
                                        {
                                            records.software_edition = book1.value.Replace(",", "|");
                                        }

                                        if (book1.key == "run_time_h")
                                        {
                                            records.run_time_h = book1.value;
                                        }

                                        if (book1.key == "run_time_min")
                                        {
                                            records.run_time_min = book1.value;
                                        }

                                        if (book1.key == "remark")
                                        {
                                            records.remark = book1.value;
                                        }

                                        if (book1.key == "Xdata")
                                        {
                                            records.Xdata = book1.value;
                                        }

                                        if (book1.key == "Ydata")
                                        {
                                            records.Ydata = book1.value;
                                        }

                                        if (book1.key == "insulation")
                                        {
                                            records.insulation = book1.value;
                                        }

                                        if (book1.key == "capacitance")
                                        {
                                            records.capacitance = book1.value;
                                        }
                                    }
                                }

                                RepairProductModel repair = new();
                                string csvLine = string.Format(
                                    "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24},{25},{26},{27},{28},{29}," +
                                    "{30},{31},{32},{33},{34},{35},{36},{37},{38},{39},{40},{41},{42}",
                                    book.WarehousingDate[..10],           // 收货日期
                                    records.repairTime,             // 维修时间
                                    (DateTime.ParseExact(DateTime.Now.ToString("yyyy/MM/dd"), "yyyy/MM/dd", CultureInfo.InvariantCulture) - DateTime.ParseExact(book.WarehousingDate[..10], "yyyy/MM/dd", CultureInfo.InvariantCulture)).Days - 1 < 7 ? "正常" : "超期",
                                    book.Product_handle, // 产品处理(是否收费)
                                    book.ShippingNumber,            // 发货编号
                                    book.Name,                      // 客户名称
                                    book.One_dimensional_code,      // 产品编码
                                    book.Product_model,             // 产品规格型号
                                    book.Product_category,          // 产品组类别
                                    records.guarantee,              // 保内/保外
                                    book.State,                     // 状态
                                    book.AssignPersonnel,           // 工程师名称
                                    catalogModel.detailchoose,      // 产品细分
                                    records.back_record,            // 回访记录
                                    records.type,                   // 类型(伺服)
                                    records.product_code,           // 产品内码
                                    records.product_date,           // 产品日期
                                    records.D2_factory,             // 二维码/外加工厂家
                                    records.question_classify,      // 问题归类
                                    records.error_type,             // 故障类型
                                    records.error_detail,           // 故障细分
                                    records.reason_detail,          // 原因细分(电机)
                                    records.error_reason,           // 故障原因(电机)
                                    records.encrypt,                // 编码器编码(电机)
                                    records.product_size,           // 器件规格
                                    records.brand,                  // 品牌
                                    records.position,               // 位号
                                    records.custom_reply_phenomenon, // 客户反应现象
                                    records.repair_phenomenon,      // 维修检测现象
                                    records.reason_analysis,        // 故障原因分析
                                    records.error_deal,             // 故障处理
                                    records.PCBsiyin,               // PCB丝印
                                    records.P172,                   // 测台标志位(驱动)
                                    records.alarm_record,           // 报警记录
                                    records.software_edition,       // 软件版本
                                    records.run_time_h,             // 运行时间h
                                    records.run_time_min,           // 运行时间min
                                    records.remark,                 // 备注
                                    records.Xdata,                  // X电阻(数字)
                                    records.Ydata,                  // Y电阻(数字)
                                    records.insulation,             // 绝缘电阻(数字)
                                    records.capacitance,            // 电容(数字)
                                    records.picAddress1);           // 图片链接
                                csvContent.AppendLine(csvLine);
                            }
                            else
                            {
                                string csvLine = string.Format(
                                    "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24},{25},{26},{27},{28},{29}," +
                                    "{30},{31},{32},{33},{34},{35},{36},{37},{38},{39},{40},{41},{42}",
                                    book.WarehousingDate[..10],           // 收货日期
                                    string.Empty,             // 维修时间
                                    (DateTime.ParseExact(DateTime.Now.ToString("yyyy/MM/dd"), "yyyy/MM/dd", CultureInfo.InvariantCulture) - DateTime.ParseExact(book.WarehousingDate[..10], "yyyy/MM/dd", CultureInfo.InvariantCulture)).Days - 1 < 7 ? "正常" : "超期",
                                    book.Product_handle, // 产品处理(是否收费)
                                    book.ShippingNumber,            // 发货编号
                                    book.Name,                      // 客户名称
                                    book.One_dimensional_code,      // 产品编码
                                    book.Product_model,             // 产品规格型号
                                    book.Product_category,          // 产品组类别
                                    string.Empty,              // 保内/保外
                                    book.State,                     // 状态
                                    book.AssignPersonnel,           // 工程师名称
                                    string.Empty,      // 产品细分
                                    string.Empty,            // 回访记录
                                    string.Empty,                   // 类型(伺服)
                                    string.Empty,           // 产品内码
                                    string.Empty,           // 产品日期
                                    string.Empty,             // 二维码/外加工厂家
                                    string.Empty,      // 问题归类
                                    string.Empty,             // 故障类型
                                    string.Empty,           // 故障细分
                                    string.Empty,          // 原因细分(电机)
                                    string.Empty,           // 故障原因(电机)
                                    string.Empty,                // 编码器编码(电机)
                                    string.Empty,           // 器件规格
                                    string.Empty,                  // 品牌
                                    string.Empty,               // 位号
                                    string.Empty, // 客户反应现象
                                    string.Empty,      // 维修检测现象
                                    string.Empty,        // 故障原因分析
                                    string.Empty,             // 故障处理
                                    string.Empty,               // PCB丝印
                                    string.Empty,                   // 测台标志位(驱动)
                                    string.Empty,           // 报警记录
                                    string.Empty,       // 软件版本
                                    string.Empty,             // 运行时间h
                                    string.Empty,           // 运行时间min
                                    string.Empty,                 // 备注
                                    string.Empty,                  // X电阻(数字)
                                    string.Empty,                  // Y电阻(数字)
                                    string.Empty,             // 绝缘电阻(数字)
                                    string.Empty,            // 电容(数字)
                                    string.Empty); // 图片链接
                                csvContent.AppendLine(csvLine);
                            }
                        }

                        string exportFolderPath = "C:\\WebSite\\XinjeMesApi\\wwwroot\\xlsx";
                        string ambin = "维修数据表" + DateTime.Now.ToString("mm-ss") + ".csv";
                        string csvFilePath = Path.Combine(exportFolderPath, ambin);
                        System.IO.File.WriteAllText(csvFilePath, csvContent.ToString(), Encoding.UTF8);
                        string downloadLink = "/xlsx/" + ambin;  // 下载链接
                        this.response.SetSuccess(downloadLink);
                    }

                    // query.ToList().OrderBy(x => x.customerLevel).ToList();
                }

                // 组员返回的内容
                else
                {
                    var query = from sr in context.MainsortRecord
                                join rp in context.RepairProduct
                                on sr.ID equals rp.ProductId
                                where sr.AssignPersonnelUserId == currentUser.UserID
                                && sr.Product_Category == MainsortRecordState.Progroup[currentUser.ProductGroup]
                                && rp.State == "0"
                                && new[] { "3", "5" }.Contains(sr.State)
                                select new RepairModel
                                {
                                    ProductId = sr.ID,
                                    WarehousingDate = sr.WarehousingDate, // 收货时间
                                    RepairData = rp.Data, // 维修记录
                                    ApplyRepairTime = rp.MaintenanceEntryTime == null ? string.Empty : rp.MaintenanceEntryTime.Value.ToString("yyyy-MM-dd") ?? string.Empty,
                                    DaysOfReceipt = (DateTime.Now.Date - DateTime.Parse(sr.WarehousingDate.Substring(0, 10)).Date).Days.ToString(),
                                    Name = sr.Name,
                                    One_dimensional_code = sr.One_Dimensional_Code,   // 一维码
                                    Product_model = sr.Product_Model,
                                    Product_category = sr.Product_Category,
                                    Product_classification = sr.Product_Classification,
                                    Product_Name = sr.Product_Name,
                                    Guarantee = sr.Guarantee,
                                    State = sr.State, // 状态
                                    Repairornot = rp.RepairOr, // 维修
                                    SkillManager = rp.SkillManager == "null" ? string.Empty : rp.SkillManager,   // 产品细分
                                    AssignPersonnel = context.MesUserRole.FirstOrDefault(x => x.ID == sr.AssignPersonnelUserId).UserName ?? string.Empty,
                                    FixUnder6 = sr.SecondaryRepairsOr == "是" ? "是" : string.Empty,
                                    Product_handle = rp.ProductHandle,
                                    FirstEnter = context.MaintenanceCost.FirstOrDefault(x => x.ID == sr.ID).Context != null ? 1 : 0,
                                    Contact_information = sr.Contact_Information,   // 客户电话
                                    CustomerLevel = sr.CustomerLevel,      // 客户级别
                                    Shipping_address = sr.Shipping_Address, // 客户地址
                                    ShippingNumber = rp.ShippingNumber,  // 发货编号
                                };
                    product_category = product_category.Equals(string.Empty) ? 0 : product_category;
                    if (product_category != 0)
                    {
                        string temp = string.Empty;
                        if (product_category == 2)
                        {
                            temp = "生产二部";
                        }
                        else if (product_category == 3)
                        {
                            temp = "生产三部";
                        }
                        else if (product_category == 4)
                        {
                            temp = "生产四部";
                        }

                        query = query.Where(x => x.Product_category.Equals(temp));
                    }

                    if (!string.IsNullOrEmpty(oneDimensionalCode))
                    {
                        query = query.Where(x => x.One_dimensional_code.Contains(oneDimensionalCode));
                    }

                    // 按照客户名称筛选
                    if (!string.IsNullOrEmpty(name))
                    {
                        query = query.Where(x => x.Name.Contains(name));
                    }

                    // 按照是否分配筛选,
                    if (allocation_name == "未分配")
                    {
                        query = query.Where(x => x.AssignPersonnel == string.Empty);
                    }
                    else if (allocation_name == "已分配")
                    {
                        query = query.Where(x => x.AssignPersonnel != string.Empty);
                    }

                    List<RepairModel> result = query.ToList();

                    if (!string.IsNullOrEmpty(chaoqi))
                    {
                        if (chaoqi == "正常")
                        {
                            result = result.Where(x => (DateTime.Now - DateTime.ParseExact(x.WarehousingDate[..10], "yyyy/MM/dd", CultureInfo.InvariantCulture)).Days < 5).ToList();
                        }
                        else if (chaoqi == "将超期")
                        {
                            result = result.Where(x => (DateTime.Now - DateTime.ParseExact(x.WarehousingDate[..10], "yyyy/MM/dd", CultureInfo.InvariantCulture)).Days <= 7 &&
                            (DateTime.Now - DateTime.ParseExact(x.WarehousingDate[..10], "yyyy/MM/dd", CultureInfo.InvariantCulture)).Days >= 5).ToList();
                        }
                        else if (chaoqi == "超期")
                        {
                            result = result.Where(x => (DateTime.Now - DateTime.ParseExact(x.WarehousingDate[..10], "yyyy/MM/dd", CultureInfo.InvariantCulture)).Days > 7).ToList();
                        }
                    }

                    // 按照日期筛选
                    if (!string.IsNullOrEmpty(warehousingDate))
                    {
                        string[] wareho = warehousingDate.Split(',');
                        result = result.Where(x => DateTime.Compare(DateTime.Parse(x.WarehousingDate[..10]), DateTime.Parse(wareho[0])) >= 0).ToList();
                        result = result.Where(x => DateTime.Compare(DateTime.Parse(x.WarehousingDate[..10]), DateTime.Parse(wareho[1])) <= 0).ToList();
                    }

                    result.Sort((a, b) => DateTime.Parse(b.ApplyRepairTime == string.Empty ? "2099-01-01 00:00:00.000" : b.ApplyRepairTime).CompareTo(DateTime.Parse(a.ApplyRepairTime == string.Empty ? "2099-01-01 00:00:00.000" : a.ApplyRepairTime)));

                    this.response.SetData(result.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList(), result.Count);

                    int count = result.Count;
                    result = result.OrderBy(x => x.Name).ToList(); // 客户名称排列
                    result = result.OrderByDescending(x => x.WarehousingDate).ToList(); // 收货时间按降序排列
                    result = result.OrderByDescending(x => x.ApplyRepairTime).ToList(); // 收费时间排序

                    this.response.SetData(result.ListPaged(currentPage, pageSize), count);
                }
            }
            catch (Exception)
            {
                this.response.SetFailed();
                return this.response;
            }

            {
            }

            return this.response;
        }

        /// <summary>
        /// 返回工程师 .
        /// <param name="product_category">产品组别 .</param>
        /// </summary>
        /// <returns> .</returns>
        [Route("api/v1/reportForms/Gongchengshi")]
        [HttpGet]
        public ResponseModel Gongchengshi(string? product_category)
        {
            List<MesUserRole12> mesUserRole1 = new();
            using (FactoryMesContext context = new())
            {
                if (product_category == "2")
                {
                    mesUserRole1 = context.MesUserRole12.FromSqlRaw("select a.GroupType, a.UserName, a.ID  from MesUserRole a  where  a.GroupType='3' and a.IsLocked=1").ToList();
                }
                else if (product_category == "3")
                {
                    mesUserRole1 = context.MesUserRole12.FromSqlRaw("select a.GroupType, a.UserName, a.ID  from MesUserRole a  where  a.GroupType='4' and a.IsLocked=1").ToList();
                }
                else if (product_category == "4")
                {
                    mesUserRole1 = context.MesUserRole12.FromSqlRaw("select a.GroupType, a.UserName, a.ID  from MesUserRole a  where  a.GroupType='5' and a.IsLocked=1").ToList();
                }
                else
                {
                    mesUserRole1 = context.MesUserRole12.FromSqlRaw("select a.GroupType, a.UserName, a.ID  from MesUserRole a  where  a.GroupType='3' or a.GroupType='4' or a.GroupType='5' and a.IsLocked=1").ToList();
                }
            }

            this.response.SetData(mesUserRole1);
            return this.response;
        }

        /// <summary>
        /// 保存维修产品列表.
        /// </summary>
        /// <param name="id">产品 id .</param>
        /// <param name="progress">产品处理 .</param>
        /// <param name="skillManager">技术对接 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/repair/saveRepairProductList")]
        [HttpGet]
        public ResponseModel SaveRepairProductList(string id, string? progress, string? skillManager)
        {
            using var context = new FactoryMesContext();
            var model = context.RepairProduct.FirstOrDefault(x => x.ProductId == id);
            var product = context.MainsortRecord.FirstOrDefault(x => x.ID == id);
            var cost = context.MaintenanceCost.FirstOrDefault(x => x.ID == id);
            if (model != null)
            {
                model.ProductHandle = progress ?? string.Empty;
                if (model.ProductHandle == "非收费")
                {
                    product.State = "5"; // 维修中（跳过状态"4",即跳过收费状态）

                    // cost.ApplyTime = DateTime.Now;
                }
                else if (model.ProductHandle == "收费")
                {
                    product.State = "5";
                }

                model.SkillManager = skillManager ?? string.Empty;
            }
            else if (model != null)
            {
                model.SkillManager = skillManager ?? string.Empty;
            }
            else
            {
                this.response.SetFailed();
            }

            context.SaveChanges();
            return this.response;
        }

        /// <summary>
        /// 0.
        /// </summary>
        /// <param name="grade">1.</param>
        /// <param name="data">2.</param>
        /// <returns>3.</returns>
        /// <exception cref="ArgumentNullException">4.</exception>
        [Route("/api/v1/repair/problemGrade")]
        [HttpPost]
        public ResponseModel ProblemClassificationList(string grade, ProblemGradeAModel data)
        {
            if (data is null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            using (FactoryMesContext context = new())
            {
                if (grade == "0")
                {
                    var info = from pg in context.ProblemGrade
                               where pg.id == "1"
                               select new ProblemGradeModel
                               {
                                   XZGradeA = pg.XZGradeA,
                                   XZGradeB = pg.XZGradeB,
                                   XZGradeC = pg.XZGradeC,
                                   XZGradeD = pg.XZGradeD,
                                   QDGradeA = pg.QDGradeA,
                                   QDGradeB = pg.QDGradeB,
                                   QDGradeC = pg.QDGradeC,
                                   QDGradeD = pg.QDGradeD,
                                   DJGradeA = pg.DJGradeA,
                                   DJGradeB = pg.DJGradeB,
                                   DJGradeC = pg.DJGradeC,
                                   DJGradeD = pg.DJGradeD,
                                   DJGradeE = pg.DJGradeE,
                               };
                    this.response.SetData(info.FirstOrDefault());
                }
                else if (grade == "1")
                {
                    var info = from pg in context.ProblemGrade
                               where pg.id == "1"
                               select new ProblemXZGradeModel
                               {
                                   XZGradeA = pg.XZGradeA,
                                   XZGradeB = pg.XZGradeB,
                                   XZGradeC = pg.XZGradeC,
                                   XZGradeD = pg.XZGradeD,
                               };
                    this.response.SetData(info.FirstOrDefault());
                }
                else if (grade == "2")
                {
                    var info = from pg in context.ProblemGrade
                               where pg.id == "1"
                               select new ProblemQDGradeModel
                               {
                                   QDGradeA = pg.QDGradeA,
                                   QDGradeB = pg.QDGradeB,
                                   QDGradeC = pg.QDGradeC,
                                   QDGradeD = pg.QDGradeD,
                               };
                    this.response.SetData(info.FirstOrDefault());
                }
                else if (grade == "3")
                {
                    var info = from pg in context.ProblemGrade
                               where pg.id == "1"
                               select new ProblemDJGradeModel
                               {
                                   DJGradeA = pg.DJGradeA,
                                   DJGradeB = pg.DJGradeB,
                                   DJGradeC = pg.DJGradeC,
                                   DJGradeD = pg.DJGradeD,
                                   DJGradeE = pg.DJGradeE,
                               };
                    this.response.SetData(info.FirstOrDefault());
                }
                else if (grade == "11")
                {
                    var entity = context.ProblemGrade.FirstOrDefault(e => e.id == "1");
                    entity.XZGradeA = data.data;
                    context.SaveChanges();
                }
                else if (grade == "12")
                {
                    var entity = context.ProblemGrade.FirstOrDefault(e => e.id == "1");
                    entity.XZGradeB = data.data;
                    context.SaveChanges();
                }
                else if (grade == "13")
                {
                    var entity = context.ProblemGrade.FirstOrDefault(e => e.id == "1");
                    entity.XZGradeC = data.data;
                    context.SaveChanges();
                }
                else if (grade == "14")
                {
                    var entity = context.ProblemGrade.FirstOrDefault(e => e.id == "1");
                    entity.XZGradeD = data.data;
                    context.SaveChanges();
                }
                else if (grade == "21")
                {
                    var entity = context.ProblemGrade.FirstOrDefault(e => e.id == "1");
                    entity.QDGradeA = data.data;
                    context.SaveChanges();
                }
                else if (grade == "22")
                {
                    var entity = context.ProblemGrade.FirstOrDefault(e => e.id == "1");
                    entity.QDGradeB = data.data;
                    context.SaveChanges();
                }
                else if (grade == "23")
                {
                    var entity = context.ProblemGrade.FirstOrDefault(e => e.id == "1");
                    entity.QDGradeC = data.data;
                    context.SaveChanges();
                }
                else if (grade == "24")
                {
                    var entity = context.ProblemGrade.FirstOrDefault(e => e.id == "1");
                    entity.QDGradeD = data.data;
                    context.SaveChanges();
                }
                else if (grade == "31")
                {
                    var entity = context.ProblemGrade.FirstOrDefault(e => e.id == "1");
                    entity.DJGradeA = data.data;
                    context.SaveChanges();
                }
                else if (grade == "32")
                {
                    var entity = context.ProblemGrade.FirstOrDefault(e => e.id == "1");
                    entity.DJGradeB = data.data;
                    context.SaveChanges();
                }
                else if (grade == "33")
                {
                    var entity = context.ProblemGrade.FirstOrDefault(e => e.id == "1");
                    entity.DJGradeC = data.data;
                    context.SaveChanges();
                }
                else if (grade == "34")
                {
                    var entity = context.ProblemGrade.FirstOrDefault(e => e.id == "1");
                    entity.DJGradeD = data.data;
                    context.SaveChanges();
                }
                else if (grade == "35")
                {
                    var entity = context.ProblemGrade.FirstOrDefault(e => e.id == "1");
                    entity.DJGradeE = data.data;
                    context.SaveChanges();
                }
                else
                {
                    this.response.SetFailed();
                }
            }

            return this.response;
        }

        /// <summary>
        /// 获取维修记录列表 .
        /// </summary>
        /// <param name="id">唯一标识 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/repair/repairRecordList")]
        [HttpGet]
        public ResponseModel RepairRecordList(string id)
        {
            using var context = new FactoryMesContext();
            var repair = context.RepairProduct.FirstOrDefault(x => x.ProductId == id);
            if (repair != null)
            {
                if (repair.Data != null && !repair.Data.Equals(string.Empty))
                {
                    this.response.SetData(JsonConvert.DeserializeObject<RepairCatalogModel>(repair.Data));
                }
            }
            else
            {
                this.response.SetFailed();
            }

            return this.response;
        }

        /// <summary>
        /// 保存维修记录列表 .
        /// </summary>
        /// <param name="environment"> 1.</param>
        /// <param name="model">2.</param>
        /// <returns>3.</returns>
        [Route("/api/v1/repair/saveRepairRecordList")]
        [HttpPost]
        public async Task<ResponseModel> SaveRepairRecordList02([FromServices] IWebHostEnvironment environment, [FromForm] RepairLogModel model)
        {
            using var context = new FactoryMesContext();

            try
            {
                var repair = context.RepairProduct.FirstOrDefault(x => x.ProductId == model.id);
                if (repair != null)
                {
                    var files = this.Request.Form.Files;
                    string fileDir = environment.WebRootPath + "\\Images\\";
                    if (Directory.Exists(fileDir) == false)
                    {
                        Directory.CreateDirectory(fileDir);
                    }

                    List<string> imgages = new();
                    foreach (var file in files)
                    {
                        var fileName = Guid.NewGuid().ToString() + file.FileName;
                        var tempPath = Path.Combine(fileDir + "\\", fileName);
                        using (var stream = new FileStream(tempPath, FileMode.Create))
                        {
                            await file.CopyToAsync(stream);
                        }

                        imgages.Add(XinjeMesProgram.XinjeMesProgram.MainParam.Path.OriginURL.Path + "/Images/" + fileName);
                    }

                    var repairLog = JsonConvert.DeserializeObject<RepairCatalogModel>(model.data);
                    repairLog.picAddress = imgages;
                    repair.Data = JsonConvert.SerializeObject(repairLog);
                    context.SaveChanges();
                }
                else
                {
                    this.response.SetFailed();
                }
            }
            catch (Exception)
            {
                this.response.SetFailed();
            }

            return this.response;
        }

        /// <summary>
        /// 改变产品状态.
        /// </summary>
        /// <param name="id">产品 id .</param>
        /// <param name="state">产品状态 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/repair/changeState")]
        [HttpPost]
        public ResponseModel ChangeState(string id, string state)
        {
            using var context = new FactoryMesContext();
            var product = context.MainsortRecord.FirstOrDefault(x => x.ID == id);
            if (product != null)
            {
                product.State = state;
                context.SaveChanges();
            }
            else
            {
                this.response.SetFailed();
            }

            return this.response;
        }

        /// <summary>
        /// 获取转交人员列表.
        /// </summary>
        /// <returns> .</returns>
        [Route("/api/v1/repair/getTransmitPeople")]
        [HttpGet]
        public ResponseModel GetTransmitPeople()
        {
            using var context = new FactoryMesContext();
            AuthContextUser currentUser = AuthContextService.CurrentUser;
            if (new[] { 0, 1, 2 }.Contains((int)currentUser.UserType))
            {
                this.response.SetData(context.MesUserRole.Select(x => new TransfereeModel(x.UserName, x.ID, x.GroupType)).ToList());
                return this.response;
            }

            var query = from u in context.MesUserRole
                        where u.UserType.Equals(currentUser.UserType)
                        && u.DepId == currentUser.DepId
                        && u.ProductGroup == currentUser.ProductGroup
                        && u.GroupType == currentUser.GroupType
                        && u.ID != currentUser.UserID
                        select new TransfereeModel(u.UserName, u.ID, u.GroupType);
            this.response.SetData(query.ToList());
            return this.response;
        }

        /// <summary>
        /// 保存转交信息.
        /// </summary>
        /// <param name="data">data .</param>
        /// <returns> .</returns>
        [Route("/api/v1/repair/saveTransmitInfo")]
        [HttpPost]
        public ResponseModel SaveTransmitInfo(TransmitModel data)
        {
            using var context = new FactoryMesContext();
            try
            {
                for (int i = 0; i < data.data.Count; i++)
                {
                    var temp = context.MainsortRecord.FirstOrDefault(x => x.ID == data.data[i]);
                    temp.AssignPersonnelUserId = data.id;
                    context.Update(temp);
                    context.SaveChanges();
                }
            }
            catch (Exception)
            {
                this.response.SetFailed();
                return this.response;
            }

            return this.response;
        }

        /// <summary>
        /// 获取分配人员列表.
        /// </summary>
        /// <returns> .</returns>
        [Route("/api/v1/repair/getAllocatePeople")]
        [HttpGet]
        public ResponseModel GetAllocatePeople()
        {
            using var context = new FactoryMesContext();
            var currentUser = AuthContextService.CurrentUser;
            if (currentUser.UserName == "唐晨")
            {
                var query = from u in context.MesUserRole
                            where u.ProductGroup == "2" && u.IsLocked == IsLocked.UnLocked
                            select new TransfereeModel(u.UserName, u.ID, u.GroupType);
                this.response.SetData(query.ToList());
            }
            else
            {
                var query = from u in context.MesUserRole
                            where (currentUser.UserID == u.CreatedByUserId
                                        || u.ID == currentUser.UserID) && u.IsLocked == IsLocked.UnLocked
                            select new TransfereeModel(u.UserName, u.ID, u.GroupType);
                this.response.SetData(query.ToList());
            }

            return this.response;
        }

        /// <summary>
        /// 保存分配信息.
        /// </summary>
        /// <param name="data">数据 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/repair/saveAllocateInfo")]
        [HttpPost]
        public ResponseModel SaveAllocateInfo(TransmitModel data)
        {
            using var context = new FactoryMesContext();
            try
            {
                foreach (string productId in data.data)
                {
                    var temp = context.MainsortRecord.FirstOrDefault(x => x.ID == productId);
                    temp.AssignPersonnelUserId = data.id;
                    context.SaveChanges();
                }
            }
            catch (Exception)
            {
                this.response.SetFailed();
                return this.response;
            }

            return this.response;
        }

        /// <summary>
        /// 获取维修报告信息 .
        /// </summary>
        /// <param name="idData">数据id .</param>
        /// <returns> .</returns>
        [Route("/api/v1/repair/repairFormData")]
        [HttpGet]
        public ResponseModel RepairFormData(string idData)
        {
            using var context = new FactoryMesContext();
            string[] stringArray = idData.Split(',');
            for (int i = 0; i < stringArray.Length; i++)
            {
                try
                {
                    Report report = context.Report.FirstOrDefault(x => x.ProductId == stringArray[i]);
                    Console.WriteLine(report);
                    if (report != null)
                    {
                        if (report.ProductGroup.Equals("生产三部"))
                        {
                            this.response.SetData(JsonConvert.DeserializeObject<ProductionDepartment3>(report.Data));
                        }
                        else if (report.ProductGroup.Equals("生产二部"))
                        {
                            this.response.SetData(JsonConvert.DeserializeObject<ProductionDepartment2>(report.Data));
                        }
                        else if (report.ProductGroup.Equals("生产四部"))
                        {
                            this.response.SetData(JsonConvert.DeserializeObject<ProductionDepartment4>(report.Data));
                        }
                        else
                        {
                            this.response.SetFailed();
                        }
                    }
                    else
                    {
                        this.response.SetFailed();
                        return this.response;
                    }
                }
                catch (Exception)
                {
                    this.response.SetFailed();
                }
            }

            return this.response;
        }

        /// <summary>
        /// 保存维修报告信息.
        /// </summary>
        /// <param name="data">数据.</param>
        /// <returns> .</returns>
        [Route("/api/v1/repair/saveRepairFormData")]
        [HttpPost]
        public ResponseModel SaveRepairFormData(RepairFormModel data)
        {
            using var context = new FactoryMesContext();

            if (!context.MainsortRecord.Where(x => x.ID == data.id).Any())
            {
                this.response.SetFailed();
                return this.response;
            }

            if (!context.Report.Where(x => x.ProductId == data.id).Any())
            {
                context.Add(new Report
                {
                    ProductId = data.id,
                    ProductGroup = context.MainsortRecord.FirstOrDefault(x => x.ID == data.id).Product_Category,
                    CreatedOn = DateTime.Now,
                    Data = data.data,
                });
            }
            else
            {
                var report = context.Report.FirstOrDefault(x => x.ProductId == data.id);
                report.Data = data.data;

                // context.Update(report);
            }

            context.SaveChanges();
            return this.response;
        }

        /// <summary>
        /// 交付维修报告信息 .
        /// </summary>
        /// <param name="id">唯一表示 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/repair/handleRepairFormData")]
        [HttpPost]
        public ResponseModel HandleRepairFormData(string id)
        {
            using var context = new FactoryMesContext();
            {
                string oldState = context.MainsortRecord.FirstOrDefault(x => x.ID == id).State;
                if (oldState == "5")
                {
                    var report = context.Report.FirstOrDefault(x => x.ProductId == id);
                    var repair = context.RepairProduct.FirstOrDefault(x => x.ProductId == id);

                    // 发货表新增记录
                    var d = context.Deliver.FirstOrDefault(x => x.ProductId == id);

                    if (d == null)
                    {
                        if (report != null)
                        {
                            repair.RepairTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            repair.RepairCompletedTime = DateTime.Now;
                            this.response = this.ChangeState(id, "6");
                            report.IsPay = true;
                            repair.State = "1";
                            context.Add(new DeliverEntity
                            {
                                ProductId = id,
                                State = "0",
                            });
                        }
                        else
                        {
                            this.response.SetError("请先编辑之后保存报告");
                            return this.response;
                        }
                    }
                    else
                    {
                        this.response.SetError("提交失败，判断值为：" + d);
                        this.response = this.ChangeState(id, "5");
                        d.State = "0";
                    }

                    // 从这里开始
                    var info1 = context.MainsortRecord.FirstOrDefault(x => x.ID == repair.ProductId);
                    var info2 = context.MaterialTracking3.OrderByDescending(x => x.EndDate).FirstOrDefault(x => x.SerialNumber == info1.One_Dimensional_Code);
                    if (info2 != null && info1.Product_Category != "生产四部")
                    {
                        info2.ScreenPrinting = repair.Data.Split("PCBsiyin")[1][11..].Split("\"}")[0];
                    }

                    context.Update(repair);
                    context.SaveChanges();
                }
                else
                {
                    this.response.SetFailed();
                }
            }

            return this.response;
        }

        /// <summary>
        /// 获取收费报告信息 .
        /// </summary>
        /// <param name="id">产品id .</param>
        /// <returns> .</returns>
        [Route("/api/v1/repair/costFormData")]
        [HttpGet]
        public ResponseModel CostFormData(string id)
        {
            using var context = new FactoryMesContext();
            var cost = context.MaintenanceCost.FirstOrDefault(x => x.ID == id);
            if (cost != null)
            {
                if (cost.Context != null)
                {
                    this.response.SetData(JsonConvert.DeserializeObject<CostReportDataModel>(cost.Context));
                }

                // 第一次
                else
                {
                    var query = from p in context.MainsortRecord
                                where p.ID == id
                                select new CostReportDataModel
                                {
                                    name = p.Name,
                                    salesman = p.Salesman,
                                    contact_infomation = p.Contact_Information,
                                    shipping_address = p.Shipping_Address,
                                    shipping_date = p.WarehousingDate,
                                };
                    this.response.SetData(query.ToList()[0]);
                }
            }
            else
            {
                this.response.SetFailed("严重错误");
            }

            return this.response;
        }

        /// <summary>
        /// 保存收费报告信息 .
        /// </summary>
        /// <param name="costFormData">Body .</param>
        /// <returns> .</returns>
        [Route("/api/v1/repair/saveCostFormData")]
        [HttpPost]
        public ResponseModel SaveCostFormData(CostFormData costFormData)
        {
            using var context = new FactoryMesContext();
            var cost = context.MaintenanceCost.FirstOrDefault(x => x.ID == costFormData.id);
            if (cost != null)
            {
                cost.Context = JsonConvert.SerializeObject(costFormData.data);
                context.SaveChanges();
            }
            else
            {
                this.response.SetFailed();
            }

            return this.response;
        }

        /// <summary>
        /// 交付收费报告信息.
        /// </summary>
        /// <param name="id">唯一标识 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/repair/handleCostFormData")]
        [HttpGet]
        public ResponseModel HandleCostFormData(string id)
        {
            using var context = new FactoryMesContext();
            var cost = context.MaintenanceCost.FirstOrDefault(x => x.ID == id);
            var sort = context.MainsortRecord.FirstOrDefault(x => x.ID == id);
            if (cost != null && sort != null)
            {
                cost.ApplyTime = DateTime.Now;
                sort.State = "4";
                context.SaveChanges();
            }
            else
            {
                this.response.SetFailed();
            }

            return this.response;
        }

        /// <summary>
        /// 生成流转码 .
        /// </summary>
        /// <param name="userId">用户Id .</param>
        /// <param name="dataIds">数据Id .</param>
        /// <returns> .</returns>
        [Route("/api/v1/repair/saveRepairFormData")]
        [HttpGet]
        public ResponseModel AveRepairFormData(string userId, string dataIds)
        {
            // string[] Ids = {};
            // string allIds = string.Join(",", Ids);
            // string dataIds = allIds;
            using var context = new FactoryMesContext();
            string[] stringArray = dataIds.Split(';');
            if (stringArray[0][..5] == "XinJe" && stringArray.Length == 1)
            {
                stringArray[0] = stringArray[0][5..];
            }

            string str = string.Empty;
            Random random = new();

            // string str = string.Empty;
            int a = random.Next(1, 999999);
            for (int i = 0; i < stringArray.Length; i++)
            {
                var rd = context.RepairProduct.FirstOrDefault(x => x.ProductId == stringArray[i]);
                var sd = context.MainsortRecord.FirstOrDefault(x => x.ID == stringArray[i]);
                var loginName = context.MesUserRole.FirstOrDefault(x => x.ID == userId);

                // var productGroup = context.Report.FirstOrDefault(x => x.ProductId == dataIds);
                if (stringArray.Length == 1)
                {
                    if (rd.ShippingNumber == null)
                    {
                        // int newNumber = NumberGenerator.GenerateNextNumber();
                        if (sd.Product_Category == "生产二部")
                        {
                            str = "SZ" + loginName.LoginName + a;
                            rd.ShippingNumber = str;
                        }
                        else if (sd.Product_Category == "生产三部")
                        {
                            str = "QD" + loginName.LoginName + a;
                            rd.ShippingNumber = str;
                        }
                        else if (sd.Product_Category == "生产四部")
                        {
                            str = "DJ" + loginName.LoginName + a;
                            rd.ShippingNumber = str;
                        }
                    }
                    else
                    {
                        if (dataIds[..5] == "XinJe")
                        {
                            if (sd.Product_Category == "生产二部")
                            {
                                str = "SZ" + loginName.LoginName + a;
                                rd.ShippingNumber = str;
                            }
                            else if (sd.Product_Category == "生产三部")
                            {
                                str = "QD" + loginName.LoginName + a;
                                rd.ShippingNumber = str;
                            }
                            else if (sd.Product_Category == "生产四部")
                            {
                                str = "DJ" + loginName.LoginName + a;
                                rd.ShippingNumber = str;
                            }
                        }
                        else
                        {
                            str = rd.ShippingNumber;
                        }

                        // response.SetData(JsonConvert.DeserializeObject<ProductionDepartment2>(productGroup.ProductGroup));
                    }
                }
                else
                {
                    if (i == 0)
                    {
                        // int newNumber = NumberGenerator.GenerateNextNumber();
                        if (sd.Product_Category == "生产二部")
                        {
                            str = "SZ" + loginName.LoginName + a;
                            rd.ShippingNumber = str;
                        }
                        else if (sd.Product_Category == "生产三部")
                        {
                            str = "QD" + loginName.LoginName + a;
                            rd.ShippingNumber = str;
                        }
                        else if (sd.Product_Category == "生产四部")
                        {
                            str = "DJ" + loginName.LoginName + a;
                            rd.ShippingNumber = str;
                        }
                    }
                    else
                    {
                        rd.ShippingNumber = str;
                    }
                }
            }

            context.SaveChanges();
            this.response.SetData(str);
            return this.response;
        }

        /// <summary>
        /// 维修数据总览 .
        /// </summary>
        /// <param name="userId">用户Id .</param>
        /// <param name="product_category">组别 .</param>
        /// <param name="warehousingDate">日期 .</param>
        /// <returns> .</returns>
        [Route("/api/v1/repair/statisticsx")]
        [HttpGet]
        public ResponseModel Statisticsx(string userId, string? product_category, string? warehousingDate)
        {
            AuthContextUser currentUser = AuthContextService.CurrentUser;
            using var context = new FactoryMesContext();
            float[] str = { 0, 0, 0, 0, 0, 0 };
            float[] str1 = { 0, 0, 0, 0, 0, 0 };
            switch (product_category)
            {
                case "2":
                    product_category = "生产二部";
                    break;
                case "3":
                    product_category = "生产三部";
                    break;
                case "4":
                    product_category = "生产四部";
                    break;
                default:
                    break;
            }

            var str3 = context.MainsortRecord.Where(x => (x.State == "3" || x.State == "4" || x.State == "5")).ToList();
            var ssc = context.MainsortRecord.Where(x => (x.State == "3" || x.State == "5")).ToList();  // 超期/将超期/正常

            if (!new int[] { 0, 1, 2, 3 }.Contains((int)currentUser.UserType))
            {
                str3 = str3.Where(x => x.AssignPersonnelUserId == userId).ToList();  // /人员/状态数据
                ssc = ssc.Where(x => x.AssignPersonnelUserId == userId).ToList();
            }

            if (!string.IsNullOrEmpty(warehousingDate))
            {
                string[] wareho = warehousingDate.Split(',');
                ssc = ssc.Where(x => DateTime.Compare(DateTime.Parse(x.WarehousingDate[..10]), DateTime.Parse(wareho[0])) >= 0).ToList();
                ssc = ssc.Where(x => DateTime.Compare(DateTime.Parse(x.WarehousingDate[..10]), DateTime.Parse(wareho[1])) <= 0).ToList();
                str3 = str3.Where(x => DateTime.Compare(DateTime.Parse(x.WarehousingDate[..10]), DateTime.Parse(wareho[0])) >= 0).ToList();
                str3 = str3.Where(x => DateTime.Compare(DateTime.Parse(x.WarehousingDate[..10]), DateTime.Parse(wareho[1])) <= 0).ToList();
            }

            if (product_category != "0")
            {
                var str33 = str3.Where(x => x.Product_Category == product_category).ToList();
                str[0] = str3.Where(x => x.Product_Category == product_category && x.State == "3").Count();
                str[1] = str3.Where(x => x.Product_Category == product_category && x.State == "4").Count();
                str[2] = str3.Where(x => x.Product_Category == product_category && x.State == "5").Count();
                str1[0] = (str[0] / (float)str33.Count) * 100;
                str1[1] = (str[1] / (float)str33.Count) * 100;
                str1[2] = (str[2] / (float)str33.Count) * 100;
                var sscx = ssc.Where(x => x.Product_Category == product_category).ToList(); // 状态/时间/组别 后的数据
                str[3] = sscx.Where(x => (DateTime.Now - DateTime.Parse(x.WarehousingDate[..10])).Days >= 7).Count();  // 超期数
                str[4] = sscx.Where(x => (DateTime.Now - DateTime.Parse(x.WarehousingDate[..10])).Days == 6 || (DateTime.Now - DateTime.Parse(x.WarehousingDate[..10])).Days == 5).Count();  // 将超期数
                str[5] = sscx.Where(x => (DateTime.Now - DateTime.Parse(x.WarehousingDate[..10])).Days < 5).Count();  // 正常数
                str1[3] = (str[3] / (float)sscx.Count) * 100;
                str1[4] = (str[4] / (float)sscx.Count) * 100;
                str1[5] = (str[5] / (float)sscx.Count) * 100;
            }
            else
            {
                str[0] = str3.Where(x => x.State == "3").Count();
                str[1] = str3.Where(x => x.State == "4").Count();
                str[2] = str3.Where(x => x.State == "5").Count();
                str[3] = ssc.Where(x => (DateTime.Now - DateTime.Parse(x.WarehousingDate[..10])).Days >= 7).Count();  // 超期数
                str[4] = ssc.Where(x => (DateTime.Now - DateTime.Parse(x.WarehousingDate[..10])).Days == 6 || (DateTime.Now - DateTime.Parse(x.WarehousingDate[..10])).Days == 5).Count();  // 将超期数
                str[5] = ssc.Where(x => (DateTime.Now - DateTime.Parse(x.WarehousingDate[..10])).Days < 5).Count();  // 正常数
                str1[0] = (str[0] / (float)str3.Count) * 100;
                str1[1] = (str[1] / (float)str3.Count) * 100;
                str1[2] = (str[2] / (float)str3.Count) * 100;
                str1[3] = (str[3] / (float)ssc.Count) * 100;
                str1[4] = (str[4] / (float)ssc.Count) * 100;
                str1[5] = (str[5] / (float)ssc.Count) * 100;
            }

            float[][] ad = { str1, str };

            this.response.SetData(ad);
            return this.response;
        }
    }
}